using System;
using System.Collections.Generic;
using System.Text;
using System.Data;using THSERP.BusinessEntities;using THSERP.BaseProvider;
using System.Windows.Forms;
using THSLib;using THSERP.BaseProvider;

namespace THSERP.Modules.Promotion
{
    public class PromotionModule : BaseModuleERP
    {
        #region Declare Constant
        //promotion type
        public const String cstPromotionTypePctOff = "PercentOff";
        public const String cstPromotionTypeAmtOff = "AmountOff";
        public const String cstPromotionTypeBuyXTogetPctOff = "BuyXTogetPctOff";
        public const String cstPromotionTypeBuyXTogetAmtOff = "BuyXTogetAmtOff";
        #endregion

        public ControlCollection BuyXGetControls = new ControlCollection();
        public ControlCollection DiscountAmountControls = new ControlCollection();
        public ControlCollection DiscountPercentControls = new ControlCollection();

        int iProductGroupID = 0;
        private DevExpress.XtraEditors.ComboBoxEdit OptionComboBox;
        private DevExpress.XtraEditors.LookUpEdit DepartmentLookUpEdit;
        private DevExpress.XtraEditors.LookUpEdit SupplierLookUpEdit;
        public PromotionModule()
        {
            Name = "Promotion";
            CurrentModuleEntity = new PromotionEntities();
            CurrentModuleEntity.Module = this;
            InitializeModule();

            OptionComboBox = (DevExpress.XtraEditors.ComboBoxEdit)Controls["fld_cmbOption"];
            DepartmentLookUpEdit = (DevExpress.XtraEditors.LookUpEdit)Controls["fld_lkeFK_ICDepartmentID"];
            SupplierLookUpEdit = (DevExpress.XtraEditors.LookUpEdit)Controls["fld_lkeFK_APSupplierID"];
            OptionComboBox.Properties.Items.AddRange(new object[] { String.Empty, "Limit day", "Reach max" });
            GetBuyXControls();
            GetDiscountAmountControls();
            GetDiscountPerecntControls();

            EnableDisableControlsByPromotionType(cstPromotionTypePctOff);
        }

        // adds, 10/07/2008
        public override void ActionNew()
        {
            base.ActionNew();
            ICPromotionsInfo objMainPromotionsInfo = (ICPromotionsInfo)CurrentModuleEntity.MainObject;
            objMainPromotionsInfo.ICPromotionEndDate = objMainPromotionsInfo.ICPromotionStartDate.AddDays(7);
            CurrentModuleEntity.UpdateMainObjectBindingSource();
        }
        #region--product promotion--

        //hieu.nguyen add,march 19,2010
        //search product by deparment,Category and supplier
        public void SearchProduct(object sender, EventArgs e)
        {
            DateTime CurrentDate = DateTime.Today.Date;
            ICProductsController objICProductsController = new ICProductsController();
            ICInventoryStocksController objICInventoryStocksController = new ICInventoryStocksController();
            List<ICProductsInfo> lstProducts = new List<ICProductsInfo>();
            
            //Gen search query_Hieu.nguyen_20/05/2010
            String strQuery = GenerateSearchQuery(THSUtil.GetTableNameFromBusinessObjectType(typeof(ICProductsInfo)));
            int deparmentID = Convert.ToInt32(DepartmentLookUpEdit.EditValue);
            int supplierID = Convert.ToInt32(SupplierLookUpEdit.EditValue);
            if (deparmentID > 0)
                strQuery += String.Format("AND ([FK_ICDepartmentID]={0})", deparmentID);
            if (supplierID > 0)
                strQuery += String.Format("AND ([FK_APSupplierID]={0})", supplierID);
            if (iProductGroupID > 0)
                strQuery += String.Format("AND ([FK_ICProductGroupID]={0})", iProductGroupID);

            DataSet ds = new ICProductsController().GetDataSet(strQuery);
            if (ds != null)
            {
                if (ds.Tables.Count > 0)
                {
                    if (OptionComboBox.SelectedIndex == 1)
                    {
                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            ICProductsInfo objICProductsInfo = (ICProductsInfo)objICProductsController.GetObjectFromDataRow(row);
                            if (objICProductsInfo != null)
                            {
                                if (DateTime.Now.CompareTo(objICProductsInfo.ICProductStockMaxDateFrom) >= 0 && DateTime.Now.CompareTo(objICProductsInfo.ICProductStockMaxDateTo) <= 0)
                                {
                                    double dbInventoryStockQty = objICInventoryStocksController.GetStockQuantityByProductAndStock(objICProductsInfo.ICProductID, objICProductsInfo.FK_ICStockID);
                                    if (dbInventoryStockQty > objICProductsInfo.ICProductStockMax)
                                    {
                                        objICProductsInfo.AASelected = false;
                                        lstProducts.Add(objICProductsInfo);
                                    }
                                }
                            }
                        }
                        //valiated
                        ((PromotionEntities)CurrentModuleEntity).ICProductsList.Invalidate(lstProducts);
                    }

                    else if (OptionComboBox.SelectedIndex == 2)
                    {
                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            ICProductsInfo objICProductsInfo = (ICProductsInfo)objICProductsController.GetObjectFromDataRow(row);
                            if (objICProductsInfo != null)
                            {
                            }
                        }
                        //valiated
                        ((PromotionEntities)CurrentModuleEntity).ICProductsList.Invalidate(lstProducts);
                    }
                    else
                    {
                        ((PromotionEntities)CurrentModuleEntity).ICProductsList.Invalidate(ds);
                        foreach (ICProductsInfo objICProductInfo in ((PromotionEntities)CurrentModuleEntity).ICProductsList)
                        {
                            objICProductInfo.AASelected = false;
                        }
                        ((PromotionEntities)CurrentModuleEntity).ICProductsList.GridView.RefreshData();

                    }
                }
            }
        }
        /// <summary>
        /// created by Hieu.nguyen
        /// created date :March 24,2010
        /// reset search control
        /// </summary>
        /// 
        public void ResetSearchProduct()
        {
            ResetSearchObject();
            iProductGroupID = 0;
        }

        #region--validate controls--
        // hieu.nguyen add,March 20,2010
        public void PromotionType_Validated(object sender, EventArgs e)
        {
            if (!Toolbar.IsNullOrNoneAction())
            {
                PromotionEntities entity = (PromotionEntities)CurrentModuleEntity;
                THSLookupEdit lke = (THSLookupEdit)sender;
                if (lke != null)
                {
                    GetBuyXControls();
                    if (lke.EditValue != lke.OldEditValue)
                    {
                        String strPromotionType = Convert.ToString(lke.EditValue);
                        EnableDisableControlsByPromotionType(strPromotionType);

                        //Reset relative fields
                        ICPromotionsInfo objPromotionsInfo = (ICPromotionsInfo)entity.MainObject;
                        objPromotionsInfo.ICPromotionDiscountPercent = 0;
                        objPromotionsInfo.ICPromotionDiscountAmount = 0;
                        objPromotionsInfo.ICPromotionDiscountQty = 1;
                        objPromotionsInfo.ICPromotionBuyX = 0;
                        objPromotionsInfo.ICPromotionTogetPctOff = 0;
                        objPromotionsInfo.ICPromotionTogetAmtOff = 0;
                        entity.UpdateMainObjectBindingSource();

                        //Recalculate product discount price
                        RecalculateDiscountPriceByPromotiontype();
                    }
                }
            }
        }

        public void PromotionDiscountAmtOff_Validated(object sender, EventArgs e)
        {
            if (!Toolbar.IsNullOrNoneAction())
            {
                RecalculateDiscountPriceByPromotiontype();
            }
        }
        //
        public void PromotionByX_Validated(object sender, EventArgs e)
        {
            if (!Toolbar.IsNullOrNoneAction())
            {
                RecalculateDiscountPriceByPromotiontype();
            }
        }
        //
        public void PromotionByXTogetAmtOff_Validated(object sender, EventArgs e)
        {
            if (!Toolbar.IsNullOrNoneAction())
            {
                RecalculateDiscountPriceByPromotiontype();
            }
        }
        public void PromtionByXTogetPctOff_Validated(object sender, EventArgs e)
        {
            if (!Toolbar.IsNullOrNoneAction())
            {
                RecalculateDiscountPriceByPromotiontype();
            }
        }
        public void PromotionDiscountPctOff_Validated(object sender, EventArgs e)
        {
            if (!Toolbar.IsNullOrNoneAction())
            {
                RecalculateDiscountPriceByPromotiontype();
            }
        }
        #endregion
        #region--calculate product promotion--
        /// <summary>
        /// created by:hieu.nguyen
        /// created date: March 25,2010
        /// Desc: calculate product price following promotion type
        /// </summary>
        public double CalculateDiscountPriceByPromotiontype(double dbProductPrice)
        {
            double dbDiscountPrice = dbProductPrice;
            PromotionEntities entity = (PromotionEntities)CurrentModuleEntity;
            ICPromotionsInfo objPromotionsInfo = (ICPromotionsInfo)entity.MainObject;
            if (objPromotionsInfo.ICPromotionTypeCombo == PromotionModule.cstPromotionTypeBuyXTogetPctOff || objPromotionsInfo.ICPromotionTypeCombo == PromotionModule.cstPromotionTypeBuyXTogetAmtOff)
            {
                objPromotionsInfo.ICPromotionDiscountQty = objPromotionsInfo.ICPromotionBuyX;
                objPromotionsInfo.ICPromotionDiscountPercent = objPromotionsInfo.ICPromotionTogetPctOff;
                objPromotionsInfo.ICPromotionDiscountAmount = objPromotionsInfo.ICPromotionTogetAmtOff;
            }
            if (objPromotionsInfo.ICPromotionDiscountPercent > 0)
                dbDiscountPrice = dbProductPrice * objPromotionsInfo.ICPromotionDiscountQty * (1 - objPromotionsInfo.ICPromotionDiscountPercent / 100);
            else
                dbDiscountPrice = dbProductPrice * objPromotionsInfo.ICPromotionDiscountQty - objPromotionsInfo.ICPromotionDiscountAmount;
            return dbDiscountPrice;
        }

        /// <summary>
        /// created by :hieu.nguyen
        /// Created date :March 25,2010
        /// desc recalculate product discount when validate controls promotion
        /// </summary>
        /// 
        public void RecalculateDiscountPriceByPromotiontype()
        {
            PromotionEntities entity = (PromotionEntities)CurrentModuleEntity;
            foreach (ICPromotionItemsInfo objPromotionItemsInfo in entity.ICPromotionItemsList)
                objPromotionItemsInfo.ICPromotionItemDiscountPrice = CalculateDiscountPriceByPromotiontype(objPromotionItemsInfo.ICPromotionItemRegularePrice);
            entity.ICPromotionItemsList.GridControl.RefreshDataSource();
        }
        #endregion
        #region--Enable Disable controls
        private void GetBuyXControls()
        {
            BuyXGetControls = new ControlCollection();
            DataSet ds = new STFieldsController().GetFieldByModuleIDAndUserGroupIDAndFieldGroup(this.ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID, "BuyX");
            if (ds != null)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Control ctrl = Controls[row["STFieldName"].ToString()];
                    if (ctrl != null)
                        BuyXGetControls.Add(ctrl.Name, ctrl);

                }
            }
        }
        private void GetDiscountAmountControls()
        {
            DiscountAmountControls = new ControlCollection();
            DataSet ds = new STFieldsController().GetFieldByModuleIDAndUserGroupIDAndFieldGroup(this.ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID, "DiscAmt");
            if (ds != null)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Control ctrl = Controls[row["STFieldName"].ToString()];
                    if (ctrl != null)
                        DiscountAmountControls.Add(ctrl.Name, ctrl);

                }
            }
        }
        private void GetDiscountPerecntControls()
        {
            DiscountPercentControls = new ControlCollection();
            DataSet ds = new STFieldsController().GetFieldByModuleIDAndUserGroupIDAndFieldGroup(this.ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID, "DiscPct");
            if (ds != null)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Control ctrl = Controls[row["STFieldName"].ToString()];
                    if (ctrl != null)
                        DiscountPercentControls.Add(ctrl.Name, ctrl);

                }
            }
        }

        private void EnableBuyXControl()
        {
            foreach (Control ctrl in BuyXGetControls.Values)
            {
                ctrl.Visible = true;
            }
        }
        private void DisableBuyXControl()
        {
            foreach (Control ctrl in BuyXGetControls.Values)
            {
                ctrl.Visible = false;
            }
        }
        private void EnableDiscountAmountControls()
        {
            foreach (Control ctrl in DiscountAmountControls.Values)
            {
                ctrl.Visible = true;
            }
        }
        private void DisableDiscountAmountControls()
        {
            foreach (Control ctrl in DiscountAmountControls.Values)
            {
                ctrl.Visible = false;
            }
        }
        private void EnableDiscountPercentControls()
        {
            foreach (Control ctrl in DiscountPercentControls.Values)
            {
                ctrl.Visible = true;
            }
        }
        private void DisableDiscountPercentControls()
        {
            foreach (Control ctrl in DiscountPercentControls.Values)
            {
                ctrl.Visible = false;
            }
        }
        //
        public void EnableDisableControlsByPromotionType(String strPromotionType)
        {
            if (strPromotionType.Equals(cstPromotionTypeAmtOff))
            {
                //enable
                EnableDiscountAmountControls();
                DisableBuyXControl();
                DisableDiscountPercentControls();
            }
            else if (strPromotionType.Equals(cstPromotionTypePctOff))
            {
                EnableDiscountPercentControls();
                DisableDiscountAmountControls();
                DisableBuyXControl();
            }
            else if (strPromotionType.Equals(cstPromotionTypeBuyXTogetAmtOff))
            {
                EnableBuyXControl();
                foreach (Control ctrl in BuyXGetControls.Values)
                {
                    if (ctrl.Name.Contains("Pct"))
                        ctrl.Visible = false;
                }
                //
                DisableDiscountAmountControls();
                DisableDiscountPercentControls();
            }
            else if (strPromotionType.Equals(cstPromotionTypeBuyXTogetPctOff))
            {
                EnableBuyXControl();
                foreach (Control ctrl in BuyXGetControls.Values)
                {
                    if (ctrl.Name.Contains("Amt"))
                        ctrl.Visible = false;
                }
                //
                DisableDiscountAmountControls();
                DisableDiscountPercentControls();
            }
            else
            {
                EnableBuyXControl();
                DisableDiscountAmountControls();
                DisableDiscountPercentControls();

            }
        }
        #endregion
        #region--Action click button--
        //add product to Promotion item list
        public void AddProductToPromotionItemList(object sender, EventArgs e)
        {
            PromotionEntities entity = (PromotionEntities)CurrentModuleEntity;
            if (String.IsNullOrEmpty(((ICPromotionsInfo)entity.MainObject).ICPromotionTypeCombo))
            {
                MessageBox.Show("Please select promotion type before adding product to list", "#Message#", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            foreach (ICProductsInfo objICProductsInfo in entity.ICProductsList)
            {
                if (objICProductsInfo.AASelected)
                {
                    if (!entity.ICPromotionItemsList.Exists("FK_ICProductID", objICProductsInfo.ICProductID))
                    {
                        ICPromotionItemsInfo objICPromotionItemsInfo = new ICPromotionItemsInfo();
                        objICPromotionItemsInfo.FK_ICProductID = objICProductsInfo.ICProductID;
                        objICPromotionItemsInfo.ICPromotionItemRegularePrice = objICProductsInfo.ICProductPrice01;
                        objICPromotionItemsInfo.ICPromotionItemDiscountPrice = CalculateDiscountPriceByPromotiontype(objICProductsInfo.ICProductPrice01);
                        entity.ICPromotionItemsList.Add(objICPromotionItemsInfo);

                    }
                }
            }
            entity.ICPromotionItemsList.GridControl.InvalidateLookupEditColumns();
            entity.ICPromotionItemsList.GridControl.RefreshDataSource();
        }

        // remove product promotion in item list
        public void DeleteProductFromPromotionItemList(object sender, EventArgs e)
        {
            PromotionEntities entity = (PromotionEntities)CurrentModuleEntity;
            int[] arrSelectRow = entity.ICPromotionItemsList.GridView.GetSelectedRows();
            List<ICPromotionItemsInfo> lstDeleteObject = new List<ICPromotionItemsInfo>();
            //get list remove
            try
            {
                if (entity.ICPromotionItemsList.Count > 0)
                {
                    if (arrSelectRow.Length == 0)
                    {
                        MessageBox.Show("Please select record to remove", "#Message#", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }
                foreach (int i in arrSelectRow)
                {
                    ICPromotionItemsInfo objICPromotionItemsInfo = (ICPromotionItemsInfo)entity.ICPromotionItemsList.GridView.GetRow(i);
                    if (objICPromotionItemsInfo != null)
                    {
                        lstDeleteObject.Add(objICPromotionItemsInfo);
                    }

                }
                //remove one by one
                foreach (ICPromotionItemsInfo objICPromotionItemsInfo in lstDeleteObject)
                {
                    int index = entity.ICPromotionItemsList.IndexOf(objICPromotionItemsInfo);
                    entity.ICPromotionItemsList.RemoveObjectFromList(index);
                    Application.DoEvents();
                }
            }
            catch (Exception ex)
            {

            }
        }
        //select all product
        public void SelectAll_Click(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.CheckEdit checkEdit = (DevExpress.XtraEditors.CheckEdit)sender;
            PromotionEntities entity = (PromotionEntities)CurrentModuleEntity;
            if (checkEdit != null)
            {
                foreach (ICProductsInfo objProductsInfo in entity.ICProductsList)
                    objProductsInfo.AASelected = checkEdit.Checked;
                entity.ICProductsList.GridControl.RefreshDataSource();
            }
        }
        //hieu.nguyen add,march 19,2010
        //show category
        public void ShowCategoryTree()
        {
            int iDepartmentID = 0;
            if (((DevExpress.XtraEditors.LookUpEdit)Controls["fld_lkICDepartments"]) != null)
                iDepartmentID = Convert.ToInt32(((DevExpress.XtraEditors.LookUpEdit)Controls["fld_lkICDepartments"]).EditValue);
            guiProductGroupTree guiProductGroupTree = new guiProductGroupTree();
            guiProductGroupTree.Module = this;
            guiProductGroupTree.ICDepartmentID = iDepartmentID;
            if (guiProductGroupTree.ShowDialog() == DialogResult.OK)
            {
                ICProductGroupsInfo objProductGroupsInfo = (ICProductGroupsInfo)guiProductGroupTree.TreeList.GetSelectedObject();
                if (objProductGroupsInfo != null)
                {
                    DevExpress.XtraEditors.TextEdit txt = (DevExpress.XtraEditors.TextEdit)this.Controls["fld_txtFK_ICProductGroupID"];
                    if (txt != null)
                        txt.Text = guiProductGroupTree.GetSelectedProductGroupName();
                    iProductGroupID = objProductGroupsInfo.ICProductGroupID;
                }
                if (((DevExpress.XtraEditors.LookUpEdit)Controls["fld_lkICDepartments"]) != null)
                    ((DevExpress.XtraEditors.LookUpEdit)Controls["fld_lkICDepartments"]).EditValue = guiProductGroupTree.ICDepartmentID;
            }
        }
        #endregion
        #endregion
    }
}
